package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.mapper.ClassroomMapper;
import cn.tedu.knows.portal.mapper.QuestionMapper;
import cn.tedu.knows.portal.mapper.UserRoleMapper;
import cn.tedu.knows.portal.model.Classroom;
import cn.tedu.knows.portal.model.User;
import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.model.UserRole;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.RegisterVO;
import cn.tedu.knows.portal.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-11-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    // 添加各种注册需要的依赖注入
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ClassroomMapper classroomMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public void registerStudent(RegisterVO registerVO) {
        // 1. 根据用户输入的邀请码查询班级信息
        QueryWrapper<Classroom> query=new QueryWrapper<>();
        query.eq("invite_code",registerVO.getInviteCode());
        Classroom classroom=classroomMapper.selectOne(query);
        // 2. 判断查询出的班级是否为空,如果是空抛出异常
        if(classroom==null){
            // 抛出异常
            throw new ServiceException("邀请码错误!");
        }
        // 3. 根据用户输入的手机号(用户名)查询用户信息
        User user=userMapper.findUserByUsername(
                registerVO.getPhone());
        // 4. 判断查询出的用户信息是否为空,如果不空表示已经注册过,抛出异常
        if(user!=null){
            throw new ServiceException("手机号已经被注册!");
        }
        // 5. 对用户输入的密码进行加密操作
        PasswordEncoder encoder=new BCryptPasswordEncoder();
        String pwd="{bcrypt}"+encoder.encode(
                registerVO.getPassword());
        // 6. 收集用户信息
        User stu=new User()
                .setUsername(registerVO.getPhone())
                .setNickname(registerVO.getNickname())
                .setPassword(pwd)
                .setClassroomId(classroom.getId())
                .setCreatetime(LocalDateTime.now())
                .setEnabled(1)
                .setLocked(0)
                .setType(0);
        // 7. 执行新增用户操作
        int num=userMapper.insert(stu);
        if(num!=1){
            throw new ServiceException("数据库忙");
        }
        // 8. 新增用户和角色的关系表
        UserRole userRole=new UserRole()
                .setUserId(stu.getId())
                .setRoleId(2);
        num=userRoleMapper.insert(userRole);
        if(num!=1){
            throw new ServiceException("数据库忙");
        }
    }

    private List<User> teachers = new CopyOnWriteArrayList<>();
    private Map<String, User> teacherMap = new ConcurrentHashMap<>();
    @Override
    public List<User> getTeachers() {
        if (teachers.isEmpty()) {
            synchronized (teachers) {
                if (teachers.isEmpty()) {
                    List<User> users = userMapper.findTeachers();
                    teachers.addAll(users);
                    for (User u : users) {
                        teacherMap.put(u.getNickname(), u);
                    }
                }
            }
        }
        return teachers;
    }

    @Override
    public Map<String, User> getTeacherMap() {
        if (teacherMap.isEmpty()) {
            getTeachers();
        }
        return teacherMap;
    }

    @Autowired
    private QuestionMapper questionMapper;
    @Override
    public UserVO getUserVO(String username) {
        //根据用户名查询用户信息
        User user = userMapper.findUserByUsername(username);
        //根据用户id查询问题数
        int questions = questionMapper.countQuestionsByUserId(user.getId());
        //(作业)根据用户id查询收藏数
        //实例化UserVO赋值并返回
        UserVO userVO = new UserVO()
                .setId(user.getId())
                .setNickname(user.getNickname())
                .setUsername(user.getUsername())
                .setQuestions(questions);
        return userVO;
    }

}
